package com.bjpowernode.dataservice.impl;

import com.bjpowernode.common.P2PConstants;
import com.bjpowernode.mapper.BidInfoMapper;
import com.bjpowernode.mapper.FinanceAccountMapper;
import com.bjpowernode.mapper.IncomeRecordMapper;
import com.bjpowernode.mapper.LoanInfoMapper;
import com.bjpowernode.model.BidInfo;
import com.bjpowernode.model.FinanceAccount;
import com.bjpowernode.model.IncomeRecord;
import com.bjpowernode.model.LoanInfo;
import com.bjpowernode.service.IncomeService;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;



@DubboService(interfaceClass = IncomeService.class)
public class IncomeServiceImpl implements IncomeService {

    @Resource
    private LoanInfoMapper loanInfoMapper;

    @Resource
    private BidInfoMapper bidInfoMapper;

    @Resource
    private IncomeRecordMapper incomeRecordMapper;

    @Resource
    private FinanceAccountMapper financeAccountMapper;

    @Transactional
    @Override
    public synchronized void  generateIncomePlan() {

        BigDecimal incomeMoney=new BigDecimal("0");
        Date incomeDate=new Date();
        Integer rows=0;
        //1.查询满标的产品
        List<LoanInfo> loanInfoList=loanInfoMapper.selectSelledLoanInfo();

        //2.查询每个产品的所有投资记录
        for(LoanInfo loanInfo:loanInfoList){
            List<BidInfo> bidInfoList=bidInfoMapper.selectAllByLoanId(loanInfo.getId());

            //3.计算每个投资记录的收益，添加到收益表
            for (BidInfo bidInfo : bidInfoList) {
                //收益=投资金额*周期*利率
                if (loanInfo.getProductType()== P2PConstants.PRODUCT_TYPE_XINSHOUBAO_0){
                    //新手宝，周期为天
                    incomeDate=DateUtils.addDays(loanInfo.getProductFullTime(),loanInfo.getCycle());
                    incomeMoney=bidInfo.getBidMoney().multiply(new BigDecimal(loanInfo.getCycle())).
                            divide(new BigDecimal("365"),2,BigDecimal.ROUND_HALF_UP).multiply(loanInfo.getRate()).
                            divide(new BigDecimal("100"),2,BigDecimal.ROUND_HALF_UP);
                }else {
                    //其他的，周期为月
                    incomeDate =DateUtils.addMonths(loanInfo.getProductFullTime(),loanInfo.getCycle());
                    incomeMoney=bidInfo.getBidMoney().multiply(new BigDecimal(loanInfo.getCycle())).
                                multiply(new BigDecimal("30")).multiply(loanInfo.getRate()).
                                divide(new BigDecimal("100"),2,BigDecimal.ROUND_HALF_UP);

                }
                IncomeRecord incomeRecord=new IncomeRecord();
                incomeRecord.setIncomeDate(incomeDate);
                incomeRecord.setIncomeMoney(incomeMoney);
                incomeRecord.setUid(bidInfo.getUid());
                incomeRecord.setLoanId(loanInfo.getId());
                incomeRecord.setBidId(bidInfo.getId());
                incomeRecord.setIncomeStatus(P2PConstants.INCOME_PLAN_0);

                rows=incomeRecordMapper.insertSelective(incomeRecord);
                if (rows<1){
                    throw new RuntimeException("生成收益计划，添加收益记录失败");
                }
            }
            //4.更新产品的状态是2
            rows=loanInfoMapper.updateStatus(loanInfo.getId(),P2PConstants.PRODUCT_TYPE_2);
            if (rows<1){
                throw new RuntimeException("生成收益计划，更新状态失败");
            }
        }

    }

    /**
     * 收益的返还
     */
    @Transactional
    @Override
    public synchronized void generateIncomeBack() {

        Integer rows =0;
        //1.获取到期的收益记录
        List<IncomeRecord> incomeExpireList = incomeRecordMapper.selectExpire();
        for (IncomeRecord ir : incomeExpireList) {
            //2.更新资金账户
            FinanceAccount account = financeAccountMapper.selectForUpdate(ir.getUid());
            if (account!=null){
               rows = financeAccountMapper.updateMoneyByIncomeBack(ir.getUid(),ir.getBidMoney(),ir.getIncomeMoney());

               if (rows<1){
                   throw new RuntimeException("收益返还，更新资金账户失败");
               }
               //3.更新income_status=1
                ir.setIncomeStatus(P2PConstants.INCOME_PLAN_1);
                incomeRecordMapper.updateByPrimaryKey(ir);
                if (rows<1){
                    throw new RuntimeException("收益返还，更新状态已返还失败");
                }
            }
        }
    }
}
